//
//  YWDoTempDeteAndUpKeepMissionTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/17.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDoTempDeteAndUpKeepMissionTableViewController.h"
#import "Masonry.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"

#import "YWWriteRuntimeCell.h"
#import "YWDropDownRunTimeCell.h"
#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"
#import "YWRuleTableViewCell.h"
#import "YWPostTroubleInfoCell.h"
#import "YWSaveButtonCell.h"

#import "YWPostTroubleTableViewController.h"
//#import "YWImageView.h"
#import "YWPhotoView.h"
//#import "YWAlertView.h"
#import "MBProgressHUD.h"
#import "YWShowPostTroubleInfoTableViewController.h"

#import "YWEquipmentManager.h"
#import "YWEquipment.h"
#import "YWDictEquipmentRule.h"
#import "YWMissionRuleResult.h"
#import "YWEquipmentMaintenanceRecord.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWEquipmentType.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWResourceManager.h"
#import "YWNotifyManager.h"
#import "YWEquipmentFieldRecord.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWDBTool.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWTroubleMissionModel.h"
#import "YWReportTroubleModel.h"
#import "YWReportTroubleManager.h"

@interface YWDoTempDeteAndUpKeepMissionTableViewController ()<YWTakePhotoCellDelegate,YWSaveButtonCellDelegate>
//选中的设备
@property (nonatomic, strong) YWEquipment *currentEquipment;
//规则
@property (nonatomic, strong) NSMutableArray* missionRuleResults;
//规则内容
@property (nonatomic, strong) NSString* missionRuleContent;

//tableView的footView
@property (nonatomic, strong) UIView* footView;

@property (nonatomic, weak) MBProgressHUD* HUD;
//报障按钮
@property (nonatomic, strong) UIButton *myTroublesButton;
//提交按钮
@property (nonatomic, strong) UIButton *finishedButton;

//@property (nonatomic, strong) NSArray *allEquipments;
//@property (nonatomic, strong) NSMutableArray *recordEquipmentIds;
//@property (nonatomic, strong) NSMutableArray *missionEquipmntIds;
//点击保存按钮的设备
//@property (nonatomic, strong) NSMutableArray *saveEquipmentArray;
//报障设备记录数组
//@property (nonatomic, strong) NSMutableArray *postTroubleRecordArray;
//扫描进入任务页面时的时间
//@property (nonatomic, assign) NSTimeInterval clientScanTime;
@end

@implementation YWDoTempDeteAndUpKeepMissionTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:self.maintenanceType];
    self.title = typeName;
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
//    _clientScanTime = [[NSDate date] timeIntervalSince1970]*1000;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView registerClass:[YWWriteRuntimeCell class] forCellReuseIdentifier:YWWriteRuntimeCellIdentifier];
    [self.tableView registerClass:[YWDropDownRunTimeCell class] forCellReuseIdentifier:YWDropDownRunTimeCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    [self.tableView registerClass:[YWSaveButtonCell class] forCellReuseIdentifier:YWSaveButtonCellIdentifier];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showTipsWhenFirstEnter];
    });
}
//#pragma mark - alert view
//- (void)showTipsWhenFirstEnter{
//    NSString *type = [YWMissionManager maintenanceTypeWithTypeId:self.maintenanceType];
//    NSString *setString = [NSString string];
//    NSString *messageString = [NSString string];
//    if([type isEqualToString:@"检测"]){
//        setString = KNotFirstEnterCheck;
//        messageString = KFirstEnterCheck;
//    }else if([type isEqualToString:@"保养"]){
//        setString = KNotFirstEnterMaintain;
//        messageString = KFirstEnterMaintain;
//    }
//    BOOL notFirstEnter = [[[NSUserDefaults standardUserDefaults] objectForKey:setString] boolValue];
//    if (!notFirstEnter) {
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:messageString preferredStyle:UIAlertControllerStyleAlert];
//        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
//        [alert addAction:[UIAlertAction actionWithTitle:@"不再提示" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:setString];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }]];
//        [self presentViewController:alert animated:YES completion:nil];
//    }
//}

//- (NSMutableArray *)saveEquipmentArray{
//    if (!_saveEquipmentArray) {
//        _saveEquipmentArray = [NSMutableArray array];
//    }
//    return _saveEquipmentArray;
//}

//- (void)setMaintenanceType:(YWMaintenanceType)maintenanceType{
//    _maintenanceType = maintenanceType;
//    _allEquipments = nil;
//    if (self.allEquArray) {
//        _allEquipments = self.allEquArray;
//    }else if (_qrCodeId) {
//        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
//    }else if (_locationId){
//        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
//    }
//    //自动保存设备
//    [self.saveEquipmentArray addObjectsFromArray:_allEquipments];
//    
//    [_allEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (_currentEquipmentId && [equipment.equipmentId isEqualToString:_currentEquipmentId]) {
//            _currentEquipment = equipment;
//        }
//        NSArray *runTimeParameterArray = [[YWEquipmentManager shareManager] equipmentFieldsWithTypeId:equipment.equipmentTypeId maintenanceTypeId:maintenanceType];
//        equipment.runTimeParameterArray = runTimeParameterArray.count?runTimeParameterArray:nil;
//    }];
//    if (_currentEquipment==nil && _allEquipments.count) {
//        _currentEquipment = _allEquipments[0];
//    }
//}

- (void)setAllEquipments:(NSArray *)allEquipments{
    _allEquipments = allEquipments;
    _currentEquipment = _allEquipments[0];
}

- (NSMutableArray *)missionRuleResults
{
    if (!_missionRuleResults) {
        NSMutableArray* missionRuleResults = [[NSMutableArray alloc] init];
        _missionRuleResults = missionRuleResults;
        NSArray* equipmentRules = [[YWEquipmentManager shareManager] rulesWithEquipmentTypeId:_currentEquipment.equipmentTypeId maintenanceTypeId:self.maintenanceType maintenanceCycleId:YWMissionCycleNull];
        
        [equipmentRules enumerateObjectsUsingBlock:^(YWDictEquipmentRule* _Nonnull rule, NSUInteger idx, BOOL* _Nonnull stop) {
            YWMissionRuleResult* missionRuleResult = [[YWMissionRuleResult alloc] init];
            missionRuleResult.content = rule.content;
            [_missionRuleResults addObject:missionRuleResult];
        }];
    }
    return _missionRuleResults;
}

- (NSString *)missionRuleContent{
    NSString *string = nil;
    NSArray *ruleArray = self.missionRuleResults;
    BOOL haveRule = ruleArray.count > 0 ? YES : NO;
    NSMutableString *ruleContent = [NSMutableString string];
    
    for (int i = 0; i < (haveRule ? ruleArray.count : 1); i++) {
        if (haveRule) {
            YWMissionRuleResult* missionRuleResult = ruleArray[i];
            string = [NSString stringWithFormat:@"%d.%@", i + 1, missionRuleResult.content];
        }else {
            string = NSLocalizedString(@"none", nil);
        }
        if (i != 0) {
            [ruleContent appendString:@"\n"];
        }
        [ruleContent appendString:string];
    }
    _missionRuleContent = [NSString stringWithFormat:@"%@",ruleContent];
    return _missionRuleContent;
}


- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH/2-20*2;
        //      报障
        _myTroublesButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _myTroublesButton.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        _myTroublesButton.layer.masksToBounds = YES;
        _myTroublesButton.layer.cornerRadius = 5.0;
        
        [_myTroublesButton setTitle:NSLocalizedString(@"postTrouble", nil) forState:UIControlStateNormal];
        [_myTroublesButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _myTroublesButton.backgroundColor = [UIColor customRedColor];
        [_myTroublesButton addTarget:self action:@selector(cliclPostTroubleEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_myTroublesButton];
        //      完成
        _finishedButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _finishedButton.frame = CGRectMake(20*2+_myTroublesButton.bounds.size.width+20, 30, buttonWidth, kButtonH);
        _finishedButton.layer.masksToBounds = YES;
        _finishedButton.layer.cornerRadius = 5.0;
        
        [_finishedButton setTitle:NSLocalizedString(@"finish", nil) forState:UIControlStateNormal];
        [_finishedButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _finishedButton.backgroundColor = [UIColor customBlueColor];
        [_finishedButton addTarget:self action:@selector(clickFinishButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_finishedButton];
    }
    return _footView;
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //选择设备
        return UITableViewAutomaticDimension;//44;
    }else if (indexPath.section==1) {
        //检测保养
        return UITableViewAutomaticDimension;//[YWRuleTableViewCell cellHeightOfRuleContent:self.missionRuleContent];
    }else if (indexPath.section == 2){
        //运行参数
        return _currentEquipment.runTimeParameterArray.count ? 75 : 44;
    }else if (indexPath.section ==3) {
        //备注
        return 90;
    }else{// if (indexPath.section == 4)
        //拍照(高度是动态变化的)
        if (indexPath.row == 0) {
            CGFloat imageH = YWPhotoSize*(_currentEquipment.totalImageNameArray.count/4+1) + YWPhotoGap*(_currentEquipment.totalImageNameArray.count/4);
            return 10*2 + imageH;
        }else{
            return UITableViewAutomaticDimension;//44;
        }
        
    }
//    else{
//        //报障设备
//        return _postTroubleRecordArray.count>0 ? 54 : 44;
//    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return _allEquipments.count;
    }else if (section==2){
        return _currentEquipment.runTimeParameterArray.count?:1;
    }else if(section==4){
        return 2;
    }else
        return 1;
//    else if (section==5){
//        return _postTroubleRecordArray.count?:1;
//    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"YWDoDeteAndUpKeepMissionTableViewControllerIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        YWEquipment *equipment = self.allEquipments[indexPath.row];
        cell.textLabel.text = equipment.equipmentName?:@"";
        cell.detailTextLabel.text = [_saveEquipmentArray containsObject:equipment] ? @"已保存" : nil;
        
        if ([equipment.equipmentId isEqualToString:_currentEquipment.equipmentId]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
    }else if (indexPath.section == 1){
        
        YWRuleTableViewCell *cell = [YWRuleTableViewCell cellWithTableView:tableView];
        cell.ruleContent = self.missionRuleContent;
        return cell;
    }else if (indexPath.section == 2){
        YWRunTimeParameter *runTimeParameter = _currentEquipment.runTimeParameterArray.count ? _currentEquipment.runTimeParameterArray[indexPath.row]:nil;
        if (runTimeParameter.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
            YWDropDownRunTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDropDownRunTimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }else{
            YWWriteRuntimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteRuntimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }
    }else if (indexPath.section == 3){
        YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.equipment = _currentEquipment;
        return cell;
    }else{// if (indexPath.section == 4)
        if (indexPath.row==0) {
            YWTakePhotoCell * cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
            cell.totalImageNameArray = _currentEquipment.totalImageNameArray;
            cell.delegate = self;
            return cell;
        }else{
            YWSaveButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:YWSaveButtonCellIdentifier];
            cell.delegate = self;
            cell.isSave = [_saveEquipmentArray containsObject:_currentEquipment] ? YES :NO;
            return cell;
        }
    }
//    else{
//        YWPostTroubleInfoCell *cell = [YWPostTroubleInfoCell cellWithTableView:tableView];
//        YWReportTroubleModel *reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
//        cell.reportTrouble = reportTrouble;
//        return cell;
//    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWEquipment *equipment = self.allEquipments[indexPath.row];
        if (_currentEquipment && _currentEquipment.equipmentTypeId != equipment.equipmentTypeId) {
            _missionRuleResults = nil;
        }
        _currentEquipment = equipment;
        [self.tableView  reloadData];
    }
//    else if (indexPath.section == 5){
//        YWReportTroubleModel *reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
//        if (reportTrouble) {
//            YWShowPostTroubleInfoTableViewController *showPostTroubleVC = [[YWShowPostTroubleInfoTableViewController alloc] init];
//            showPostTroubleVC.reportTrouble = reportTrouble;
//            showPostTroubleVC.delegate = self;
//            [self.navigationController pushViewController:showPostTroubleVC animated:YES];
//        }
//    }
}

#pragma mark - tableView.headerView

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWDoDeteAndUpKeepMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
    
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    }else if (section==1){
        NSString *typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:self.maintenanceType];
        return [NSString stringWithFormat:@"%@项",typeName];
    }else if (section==2){
        return NSLocalizedString(@"runtimeParameter", nil);//@"运行参数";
    }else if (section==3){
        return NSLocalizedString(@"note", nil);//@"备注";
    }else{// if (section==4)
        return NSLocalizedString(@"takePhotoToUpload", nil);//@"拍照上传";
    }
//    else{
//        return @"报障设备";
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    _currentEquipment.totalImageNameArray = arr;
    [self.tableView reloadData];
}

//#pragma mark - clickCancelThePostTroubleMissionDelegate
//- (void)clickCancelTheReportTrouble:(YWReportTroubleModel*)reportTrouble{
//    if ([_postTroubleRecordArray containsObject:reportTrouble]) {
//        [[YWReportTroubleManager shareManager] deleteReportTroubleWithTroubleId:reportTrouble.troubleId orUniqueTag:reportTrouble.uniqueTag];
//        [_postTroubleRecordArray removeObject:reportTrouble];
//        [self.tableView reloadData];
//    }
//}

#pragma mark - YWSaveButtonCellDelegate
- (void)clickCancelButtonEvent:(UIButton *)button{
    if ([_saveEquipmentArray containsObject:_currentEquipment]) {
        [_saveEquipmentArray removeObject:_currentEquipment];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"cancelSaveSucceed", nil)];
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"failedAndTryAgain", nil)];
    }
}

- (void)clickSaveButtonEvent:(UIButton *)button{
    if ([YWCommonTool isContainsEmoji:_currentEquipment.psText]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_currentEquipment.psText.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    __block BOOL isRequire = YES;
    //__block NSString *reasonable = nil;
    [_currentEquipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
        if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
            isRequire = NO;
            *fieldStop = YES;
        }
    }];
    if (!isRequire) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    
    if (!_saveEquipmentArray) {
        _saveEquipmentArray = [NSMutableArray array];
    }
    if (_currentEquipment) {
        if (![_saveEquipmentArray containsObject:_currentEquipment]) {
            [_saveEquipmentArray addObject:_currentEquipment];
        }
        [self.tableView reloadData];
        //下面这个刷新会导致调用cell的initWithStyle就重新构建了cell，导致图片消失
        //[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"saveSucceed", nil)];
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"noEquipmentToSelect", nil)];
    }
}

//#pragma mark - YWPostTroubleVCDelegate
//- (void)passBackReportTrouble:(YWReportTroubleModel*)reportTrouble{
//    //报修记录
//    if (!_postTroubleRecordArray) {
//        _postTroubleRecordArray = [NSMutableArray array];
//    }
//    if (reportTrouble) {
//        [_postTroubleRecordArray addObject:reportTrouble];
//        [self.tableView reloadData];
//    }
//}

#pragma mark - buttonAction
- (void)cliclPostTroubleEvent:(UIButton *)sender{
    NSArray *allEquipmentArray = nil;
    if (_qrCodeId) {
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
    }else if (_locationId){
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
    }
//    YWEquipment *currentEqu = nil;
//    if (_currentEquipment && allEquipmentArray.count) {
//        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", _currentEquipment.equipmentId];
//        NSArray *array = [allEquipmentArray filteredArrayUsingPredicate:searchPredicate];
//        if (array.count>=1) {
//            currentEqu = array[0];}
//    }
    YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];
    postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil; //currentEqu ? currentEqu:(allEquipmentArray.count ? allEquipmentArray[0] : nil);
    postTroublevc.equipmentArray = allEquipmentArray;
    postTroublevc.qrCodeId = _qrCodeId;
    postTroublevc.locationId = _locationId;
    postTroublevc.shouldPopBack = YES;
    postTroublevc.delegate = (id<YWPostTroubleVCDelegate>)self.tempDeteAndUpKeepEquTypeVC;
    [self.navigationController pushViewController:postTroublevc animated:YES];
}

- (void)clickFinishButtonEvent:(UIButton *)sender{
    [self.view endEditing:YES];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"equipmentTypeId", _currentEquipment.equipmentTypeId];
    NSArray *currentSaveArray = [[self.saveEquipmentArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    if (currentSaveArray.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSaveTheWritings", nil)];
        return;
    }
    __block BOOL isRequire = YES;
    __block NSString *reasonable = nil;
    __block BOOL containEmoji = NO;
    [currentSaveArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([YWCommonTool isContainsEmoji:equipment.psText]) {
            containEmoji = YES;
            *stop = YES;
        }
        if (equipment.psText.length > 100) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
            return;
        }
        [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
            if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
                isRequire = NO;
                *fieldStop = YES;
                *stop = YES;
            }
            if (field.fieldType.fieldTypeId==YWEquipmentFieldTypeIdNumber && (field.maxFieldValue!=0 || field.minFieldValue!=0) && field.fieldValue.length>0 && ([field.fieldValue integerValue]>field.maxFieldValue||[field.fieldValue integerValue]<field.minFieldValue)) {
                reasonable = [NSString stringWithFormat:@"%@(%@)",field.fieldName,equipment.equipmentName];
                //*stop = YES;
            }
            if ([YWCommonTool isContainsEmoji:field.fieldValue]){
                containEmoji = YES;
                *stop = YES;
            }
        }];
    }];
    
    if (!isRequire) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    if (containEmoji) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (reasonable.length>0) {
        NSString *tips = [NSString stringWithFormat:@"%@%@",reasonable,NSLocalizedString(@"valueNotInReasonableRangeAndMakeSureToCommit", nil)];
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tips preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
//            [self commitRecord];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
//        [self commitRecord];
    }
}

//- (void)commitRecord{
//    NSString* content = [NSString stringWithFormat:@"提交记录，请确定"];
//    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:content preferredStyle:UIAlertControllerStyleAlert];
//    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
//    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.HUD show:YES];
//        //上传报障
//        [self.postTroubleRecordArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                NSArray *troublePicureArray = [[YWDBTool shareDBTool] picturesWithMissionId:reportTrouble.troubleId maintenanceType:reportTrouble.maintenanceTypeId];
////                [[YWMissionManager shareManager] startUploadRecords:nil Mission:reportTrouble pictures:troublePicureArray];
//                [[YWReportTroubleManager shareManager] startUploadReportTrouble:reportTrouble pictures:troublePicureArray];
//            });
//        }];
//        
//        [_saveEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
//            YWMaintenanceMission *maintenanceMission = [self createTempMaintenanceMissionWithType:self.maintenanceType];
//            maintenanceMission.equipmentTypeId = equipment.equipmentTypeId;
//            
//            __block YWEquipmentMaintenanceRecord* record = [self createEquipmentMaintenanceRecordsWithMission:maintenanceMission equipment:equipment];
//            __block NSArray* pictures = [self createPictureWithMission:maintenanceMission equipment:equipment record:record];
//            __block NSArray* equipmentFields = [self createEquipmentFieldsRecordsWithRecord:record equipment:equipment];
//            
////            if (maintenanceMission.maintenanceTypeId == YWMaintenanceTypeDetection) {
////                [[YWEquipmentManager shareManager] updateLastMaintenanceTimeWithEquipments:_saveEquipmentArray maintenceTime:maintenanceMission.finishTime executorName:[YWLoginTool loginUser].userName];
////            }
//            
//            BOOL saveMission = [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:maintenanceMission? @[ maintenanceMission ] : nil];
//            BOOL saveMaintenanceRecord = [YWDetectAndUpkeepManager updateMaintenanceRecords:record?@[record]:nil maintenanceTypeId:maintenanceMission.maintenanceTypeId];
//            BOOL saveEquipmetFieldRecord = [[YWMissionManager shareManager] updateEquipmentFieldRecords:equipmentFields];
//            
//            BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
//            if (saveMission && saveMaintenanceRecord && savePicturesToDB && saveEquipmetFieldRecord) {
//                [self.HUD hide:YES];
//                //提交记录
//                [[YWDetectAndUpkeepManager alloc] startUploadDetectAndUpkeepRecords:record?@[record]:nil maintenanceMission:maintenanceMission pictures:pictures];
//                
//            }else {
//                [self.HUD hide:YES];
//                YWLog(@"保存数据库失败");
//                [YWCommonTool showTextHUDWithContent:kTextSubmitTaskFail];
//            }
//        }];
//        [YWCommonTool showTextHUDWithContent:kTextCommitSuccess];
//        [self.navigationController popViewControllerAnimated:YES];
//    }]];
//    [self presentViewController:alertController animated:YES completion:nil];
//}
//
//- (YWMaintenanceMission*)createTempMaintenanceMissionWithType:(YWMaintenanceType)maintenanceType{
//    YWMaintenanceMission *maintenanceMission = [[YWMaintenanceMission alloc]init];
//    maintenanceMission.missionId = -1 * [YWCommonTool randNumber];
//    maintenanceMission.maintenanceTypeId = maintenanceType;
//    maintenanceMission.missionStatus = YWMissionStatusFinished;
//    
//    if (maintenanceType == YWMaintenanceTypeDetection) {
//        maintenanceMission.missionName = @"临时检测任务";
//    }else{
//        maintenanceMission.missionName = @"临时保养任务";
//    }
//    maintenanceMission.equipmentQuantity = 1;
//    maintenanceMission.completedQuantity = 1;
//    maintenanceMission.startTime = [[NSDate date] timeIntervalSince1970] * 1000;
//    maintenanceMission.createTime = maintenanceMission.startTime;
//    maintenanceMission.finishTime = maintenanceMission.startTime;
//    maintenanceMission.updateTime = maintenanceMission.startTime;
//    maintenanceMission.cutoffTime = maintenanceMission.startTime;
//    YWHandler *mySelf = [[YWHandler alloc]init];
//    YWLoginUser *user = [YWLoginTool loginUser];
//    mySelf.uniqueId = user.uniqueId;
//    mySelf.userName = user.userName;
//    mySelf.headIcon = user.headIcon;
//    mySelf.mobile = user.mobile;
//    maintenanceMission.creator = mySelf;
//    maintenanceMission.executorIds = [@(user.uniqueId) stringValue];
//    maintenanceMission.read = YES;
//    
//    NSInteger locationId = 0;
//    if (_qrCodeId) {
//        locationId = [[YWEquipmentManager shareManager]locationIdWithQrcodeId:_qrCodeId];
//    }else if (_locationId){
//        locationId = _locationId;
//    }
//    
//    YWBuilding* building = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
//    maintenanceMission.buildingId = building.buildingId;
//    return maintenanceMission;
//}
//
//- (NSArray*)createPictureWithMission:(YWMaintenanceMission*)mission equipment:(YWEquipment*)equipment record:(YWEquipmentMaintenanceRecord*)record
//{
//    NSMutableArray* pictures = [NSMutableArray array];
//    for (int i = 0; i < [equipment.totalImageNameArray count]; i++) {
//        YWPicture* picture = [[YWPicture alloc] init];
//        picture.pictureId = [YWCommonTool randStringId];
//        picture.pictureName = equipment.totalImageNameArray[i];
//        picture.isLocalImage = YES;
//        picture.uploadStatus = YWPictureUploadStatusNull;
//        picture.missionId = mission.missionId;
//        picture.maintenanceType = mission.maintenanceTypeId;
//        picture.equipmentId = record.equipmentId;
//        picture.recordId = record.recordId;
//        [pictures addObject:picture];
//    }
//    return pictures;
//}
//- (YWEquipmentMaintenanceRecord*)createEquipmentMaintenanceRecordsWithMission:(YWMaintenanceMission*)mission equipment:(YWEquipment*)equipment
//{
//    YWEquipmentMaintenanceRecord* maintenanceRecord = [[YWEquipmentMaintenanceRecord alloc] init];
//    //这里原来有减idx  -idx（改了时间戳的方法后就删掉了）
//    maintenanceRecord.recordId = [YWCommonTool negativeTimestampId] ;
//    /**任务ID*/
//    maintenanceRecord.missionId = mission.missionId;
//    NSString *uniqueTag = [YWCommonTool randStringId];
//    maintenanceRecord.maintenanceTypeId = mission.maintenanceTypeId;
//    maintenanceRecord.uniqueTag = uniqueTag;
//    maintenanceRecord.equipmentId = equipment.equipmentId;
//    maintenanceRecord.note = [equipment.psText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//    maintenanceRecord.completeTime = [[NSDate date] timeIntervalSince1970] * 1000;
//    maintenanceRecord.clientScanTime = _clientScanTime;
//    maintenanceRecord.handlerName = [YWLoginTool loginUser].userName;
//    maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusNormal;
//    maintenanceRecord.uploadStatus = YWEquipmentMaintenanceRecordUploadStatusUploading;
//    
//    NSString *dayMonthString = [YWCommonTool showTime:maintenanceRecord.completeTime / 1000 andFormatter:KTimeFormatDayMonth];
//    maintenanceRecord.dayMonthString = dayMonthString;
//    //检测保养都是正常完成状态，没有故障状态
//    //if (self.postTroubleRecordArray.count>0) {
//        //maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusTrouble;
//    //}
//    
//    return maintenanceRecord;
//}
//- (NSArray*)createEquipmentFieldsRecordsWithRecord:(YWEquipmentMaintenanceRecord*)record equipment:(YWEquipment*)equipment{
//    __block NSMutableArray* fieldsArray = [[NSMutableArray alloc]init];
//    __block NSMutableArray* allFieldRecords = [NSMutableArray array];
//    
//    [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull stop) {
//        YWEquipmentFieldRecord *fieldRecord = [[YWEquipmentFieldRecord alloc]init];
//        fieldRecord.uniqueTag = record.uniqueTag;
//        fieldRecord.fieldId = field.fieldId;
//        fieldRecord.fieldName = field.fieldName;
//        if (field.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
//            fieldRecord.fieldTypeId = YWEquipmentFieldTypeIdDownSelect;
//            fieldRecord.fieldOption = field.fieldOptionValue;
//        }else{
//            fieldRecord.fieldValue = field.fieldValue;
//        }
//        fieldRecord.maintenanceTypeId = self.maintenanceType;
//        [fieldsArray addObject:fieldRecord];
//        [allFieldRecords addObject:fieldRecord];
//    }];
//    record.equipmentFieldRecord = fieldsArray;
//    return allFieldRecords;
//}
//
//- (MBProgressHUD*)HUD
//{
//    if (!_HUD) {
//        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
//        hud.labelFont = kHUDLabelFont;
//        hud.labelText = kTextSubmitTask;
//        hud.dimBackground = YES;
//        // hud.animationType = MBProgressHUDAnimationZoom;
//        _HUD = hud;
//        _HUD.tag = kMBProgressHUDTag;
//        [self.navigationController.view addSubview:hud];
//    }
//    return _HUD;
//}

#pragma mark - alert view
- (void)showTipsWhenFirstEnter{
    BOOL notFirstEnter = [[[NSUserDefaults standardUserDefaults] objectForKey:KNotFirstEnterDoMissionVC] boolValue];
    if (!notFirstEnter) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(KFirstEnterDoMissionVCTips, nil) preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"dontPromptAgain", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KNotFirstEnterDoMissionVC];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
